import { reqPublishWork } from '@/api/hosting-style';
import { initQiniu, uploadFile } from '@/api/qiniu/upload';
import { HOSTING_STYLE_VIDEO_SIZE_LIMIT } from '@/assets/constant/config-constants';
import { hostingStyleStore } from '@/stores/hosting-style-store';
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings';
import {
  reqSecurityMsgCheck
} from '@/api/system.js'
import { validateCheckResult } from '@/utils/index.js';

let eventChannel: WechatMiniprogram.EventChannel;

Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store: hostingStyleStore,
    actions: ['resetWorkList', 'getWorkList'],
  },
  data: {
    maxImgCount: 9,
    type: 'image' as 'image' | 'video',
    imageList: [] as string[],
    video: '',
    isPlayingVideo: false,
    cover: '',
  },
  onLoad(options) {
    eventChannel = this.getOpenerEventChannel();
    const { type, chosenImgList, chosenVideo } = options;
    this.setData({
      type: type,
      imageList: JSON.parse(chosenImgList || '[]'),
      video: chosenVideo,
    });
  },
  async onClickAddImage() {
    const chosenImgList = (
      await wx.chooseMedia({
        mediaType: ['image'],
        count: this.data.maxImgCount - this.data.imageList.length,
      })
    ).tempFiles.map((file) => file.tempFilePath);
    this.setData({
      imageList: this.data.imageList.concat(chosenImgList),
    });
  },
  async onClickImage(e: WechatMiniprogram.TouchEvent) {
    const src = e.currentTarget.dataset.src;
    const { tapIndex } = await wx.showActionSheet({
      itemList: ['预览', '删除'],
    });
    if (tapIndex === 0) {
      wx.previewImage({
        urls: this.data.imageList,
        current: src,
      });
      return;
    }

    this.setData({
      imageList: this.data.imageList.filter((item: string) => item !== src),
    });
  },
  async onClickAddVideo() {
    wx.showLoading({
      title: '加载中...',
    });
    const chooseMediaRes = await wx.chooseMedia({
      mediaType: ['video'],
      maxDuration: 60,
      camera: 'back',
    });
    wx.hideLoading();
    const size = chooseMediaRes.tempFiles[0].size;
    if (size > HOSTING_STYLE_VIDEO_SIZE_LIMIT) {
      wx.showToast({
        title: `视频大小不能超过${HOSTING_STYLE_VIDEO_SIZE_LIMIT / 1024 / 1024}M`,
        icon: 'none',
      });
      return;
    }

    this.setData({
      video: chooseMediaRes.tempFiles[0].tempFilePath,
    });
  },
  async onClickVideo() {
    const { tapIndex } = await wx.showActionSheet({
      itemList: ['预览', '删除', '自定义封面'],
    });
    if (tapIndex === 0) {
      const videoCtx = wx.createVideoContext('video');
      this.setData({
        isPlayingVideo: true,
      });
      videoCtx.requestFullScreen({
        direction: 0,
      });
      videoCtx.play();
      return;
    }
    if (tapIndex === 1) {
      this.setData({
        video: '',
      });
      return;
    }

    const chosenImg = await wx.chooseMedia({
      mediaType: ['image'],
      count: 1,
    });
    this.setData({
      cover: chosenImg.tempFiles[0].tempFilePath,
    });
  },
  onFullScreenChange(e: WechatMiniprogram.VideoFullScreenChange) {
    if (!e.detail.fullScreen) {
      this.setData({
        isPlayingVideo: false,
      });
      const videoCtx = wx.createVideoContext('video');
      videoCtx.stop();
      videoCtx.seek(0);
    }
  },
  onInputTitle(e: WechatMiniprogram.Input) {
    this.setData({
      title: e.detail.value,
    });
  },
  onInputContent(e: WechatMiniprogram.Input) {
    this.setData({
      content: e.detail.value,
    });
  },
  async publishImage() {
    await initQiniu();
    const imageList = await Promise.all(
      this.data.imageList.map(async (img: string) => {
        if (img.startsWith('https://ustatic')) {
          return img;
        }

        const res = await uploadFile([img]);
        return res[0].fileURL;
      }),
    );

    const res = await reqPublishWork({
      title: this.data.title,
      cover: imageList[0],
      content: this.data.content,
      imageList,
    });

    if (res.code === 200) {
      return true;
    }

    return false;
  },
  async publishVideo() {
    await initQiniu();
    const video = (await uploadFile([this.data.video]))[0].fileURL;
    const cover = this.data.cover ? (await uploadFile([this.data.cover]))[0].fileURL : video + '?vframe/jpg/offset/1';
    const res = await reqPublishWork({
      title: this.data.title,
      cover,
      content: this.data.content,
      video: video,
    });

    if (res.code === 200) {
      return true;
    }

    return false;
  },
  async onClickPublish() {
    if (!this.data.title) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none',
      });
      return;
    }
    if (!this.data.content) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none',
      });
      return;
    }
    try {
      const checkRes = await reqSecurityMsgCheck(this.data.title + this.data.content);
      if (!validateCheckResult(checkRes.data.data?.msg_sec_check)) {
        throw new Error('内容非法');
      }
      wx.showLoading({
        title: '发布中...',
      });
      let res;
      if (this.data.type === 'image') {
        res = await this.publishImage();
      } else {
        res = await this.publishVideo();
      }
      wx.hideLoading();
      if (res) {
        wx.showToast({
          title: '发布成功',
        });
        this.resetWorkList();
        this.getWorkList();
        wx.navigateBack();
      } else {
        wx.showToast({
          title: '发布失败',
          icon: 'none',
        });
      }
    } catch (err) {
      console.log(err);
      wx.showToast({
        title: '内容非法!',
        icon: 'error'
      });
    }
  },
});
